<template>
  <view class="page">
    <view class="logo-warpper">
      <image class="logo" src="/static/logo.png" />
    </view>

    <button class="btn-login" @click="onLoginOpenId">手机号快捷登录</button>
    <!-- <button v-if="isAgree" class="login-btn" open-type="getPhoneNumber" @getphonenumber="getPhoneNumber">手机号快捷登录</button> -->
    <!-- <button class="login-btn" @click="onUserProfile()">获取头像昵称</button> -->

    <view class="protocol">
      <view class="check" @click="onAgree()">
        <image class="check-img" :src="isAgree ? '/static/images/check_foc.png' : '/static/images/check_nor.png'" />
        <text>请阅读并同意</text>
      </view>

      <text class="txt" @click.stop="onProtocol(0)">《用户协议》</text>
      <text>与</text>
      <text class="txt" @click.stop="onProtocol(1)">《隐私政策》</text>
    </view>
    <uni-popup ref="userProfileRef" type="center" :isMaskClick="false">
      <TipsPop tipsText="是否同意获取您的昵称、头像等信息" confirmText="同意" :isShowCancel="true" @popCancel="onCancelPop" @popConfirm="onConfirmPop" />
    </uni-popup>
  </view>
</template>

<script setup>
import { ref, reactive } from 'vue';
import TipsPop from '@/components/TipsPop.vue';
import { onLoad } from '@dcloudio/uni-app';

const userProfileRef = ref();
const isAgree = ref(false);
let loginInfo = reactive({});
const fromRef = ref(0);

onLoad((options) => {
  console.log('接收参数：', options);
  fromRef.value = options.from;
});

const onUserProfile = () => {
  uni.getUserProfile({
    desc: '获取你的昵称、头像、地区及性别',
    success: (res) => {
      console.log('getUserProfile获取微信用户信息：', JSON.stringify(res));
      if (res.errMsg == 'getUserProfile:ok') {
        const userInfo = res.userInfo;
        loginInfo.pic = userInfo.avatarUrl;
        loginInfo.nickName = userInfo.nickName;
        uni.setStorageSync('loginResult', loginInfo);

        onLoginSuccess();
      }
    },
    fail: (err) => {
      console.log('getUserProfile获取微信用户信息异常：', err); // {errMsg: "getUserProfile:fail auth deny"}
      uni.hideLoading();
      onLoginSuccess();
    }
  });
};

const onLoginSuccess = () => {
  uni.showToast({
    title: '登录成功',
    icon: 'none',
    complete() {
      console.log('登录成功，跳转');
      setTimeout(() => {
        if (fromRef.value == 1) {
          var pages = getCurrentPages();
          var beforePage = pages[pages.length - 2]; //上一个页面，当前页面：pages.length - 1
          var object = {
            from: 1
          };
          beforePage.onShow(object);
          uni.navigateBack();
        } else {
          uni.switchTab({
            url: '/pages/index/index'
          });
        }
      }, 1000);
    }
  });
};

// 获取openid
const onLoginOpenId = () => {
  if (!isAgree.value) {
    uni.showToast({
      title: '请阅读并同意《用户协议》与《隐私政策》',
      icon: 'none'
    });
    return;
  }
  uni.showLoading({ title: '' });
  uni.login({
    provider: 'weixin',
    success: (res) => {
      console.log('1登录login:', res); // {errMsg: "login:ok", code: "0d3k15100snN0T1d8y100hSPwO1k151i"}
      onLogin(res.code);
    },
    fail: (err) => {
      console.log('1登录err:', err);
      uni.hideLoading();
    }
  });
};

const onLogin = (code) => {
  http
    .request({
      url: '/wechat/login',
      method: 'post',
      data: {
        jscode: code
      }
    })
    .then(({ data }) => {
      console.log('登录接口：', data); //{"code":"00000","msg":null,"data":{"openid":"owbE85CCNPOcigBhnoH3gAemP0Xc","session_key":"I2uXT/1+Khfaf4fV8MFxng==","unionid":"oGaS8vsLwp5qBgVfEDmlbZrMiD-E","errcode":null,"errmsg":null,"jscode":null},"version":"mall.v241010","timestamp":null,"sign":null,"fail":false,"success":true}
      uni.hideLoading();
      if (!data) return;

      const token = data.userId;
      const expires = 2592000;
      data.accessToken = token;
      data.refreshToken = token;
      data.expiresIn = expires;
      const expiresTimeStamp = (expires * 1e3) / 2 + new Date().getTime();
      loginInfo = data;
      uni.setStorageSync('loginResult', data);
      uni.setStorageSync('hadLogin', true);
      uni.setStorageSync('expiresTimeStamp', expiresTimeStamp);
      uni.setStorageSync('Token', token);
      uni.setStorageSync('openId', token);

      if (!data.userInfo) {
        userProfileRef.value.open();
      } else {
        onLoginSuccess();
      }
    })
    .catch((err) => {
      uni.hideLoading();
      console.log('0微信登录异常：', err); //{errno: 600001, errMsg: "request:fail -102:net::ERR_CONNECTION_REFUSED"}
      uni.showToast({
        title: err.errMsg || '',
        icon: 'none'
      });
    });
};

// 获取手机号
const getPhoneNumber = (e) => {
  if (e.detail.errMsg == 'getPhoneNumber:ok') {
    e.detail.encrypted = e.detail.encryptedData;
    console.error(e.detail);
  } else {
    uni.showToast({
      title: '请授权手机号',
      icon: 'none'
    });
  }
};

const onAgree = (e) => {
  isAgree.value = !isAgree.value;
};

const onProtocol = (index) => {
  const url = index == 0 ? 'https://pinduoduo.com/' : 'https://www.jd.com/';
  const title = index == 0 ? '用户协议' : '隐私政策';
  uni.navigateTo({
    url: '../webView/webView?url=' + url + '&title=' + title
  });
};

const onConfirmPop = () => {
  console.log('确定');
  onUserProfile();
  userProfileRef.value.close();
};

const onCancelPop = () => {
  userProfileRef.value.close();
  onLoginSuccess();
};
</script>

<style lang="scss" scoped>
@import './login.scss';
</style>
